package com.lingyue.commons.okhttp;

import com.lingyue.commons.enums.ResultCodeEnum;
import com.lingyue.commons.exceptions.CommException;
import okhttp3.*;
import okhttp3.Request.Builder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 *
 * @Description: TODO
 * @Author: BaiJinhua
 * @Date: 2019/12/9 19:57
 * @See: com.lingyue.cpd.dump
 * @Version: 1.0
 * Copyright: Copyright (c) 2019
 */
public class OkHttpHelper {
    private static final Logger log = LoggerFactory.getLogger(OkHttpHelper.class);
    private static final MediaType XML_TYPE = MediaType.parse("application/xml;charset=utf-8");
    private static final MediaType JSON_TYPE = MediaType.parse("application/json;charset=utf-8");

    private OkHttpHelper() {
    }

    private static final OkHttpClient getInstance() {
        return OkHttpClientHolder.defaultClient;
    }

    public static String get(String url) throws CommException {
        log.info("RequestUrl:{}", url);

        try {
            HttpUrl httpUrl = HttpUrl.get(url);
            Request request = (new Builder()).url(httpUrl).get().build();
            Response response = getInstance().newCall(request).execute();
            String responseStr = response.body().string();
            log.info("ResponseBody:{}", responseStr);
            return responseStr;
        } catch (IOException var5) {
            log.error(var5.getMessage());
            throw new CommException(ResultCodeEnum.ERROR);
        }
    }

    public static String postXml(String url, String xml) throws CommException {
        log.info("RequestXmlBody:{}", xml);
        RequestBody requestBody = RequestBody.create(XML_TYPE, xml);
        return post(url, requestBody, null);
    }

    public static String postJson(String url, String json) throws CommException {
        log.info("RequestJsonBody:{}", json);
        RequestBody requestBody = RequestBody.create(JSON_TYPE, json);
        return post(url, requestBody, "Basic ZWxhc3RpYzpScTNRQVo2QWFVcXRxS0owb3Fzbg==");
    }

    public static String postJson(String url, String json, String token) throws CommException {
        log.info("RequestJsonBody:{}", json);
        RequestBody requestBody = RequestBody.create(JSON_TYPE, json);
        return post(url, requestBody, token);
    }

    public static String post(String url, RequestBody requestBody, String token) throws CommException {
        log.info("RequestUrl:{}", url);

        try {
            Builder builder = new Builder();
            if (StringUtils.isNotBlank(token)) {
                builder.addHeader("Authorization", token);
            }
            Request request = builder
                    .url(url)
                    .post(requestBody).build();
            Response response = getInstance().newCall(request).execute();
            String traceId = response.header("X-B3-TraceId");
            if(StringUtils.isNotBlank(traceId)) {
                log.info("traceId:{}",traceId);
            }
            String responseStr = response.body().string();
            log.info("ResponseBody:{}", responseStr);
            return responseStr;
        } catch (IOException var5) {
            log.error(var5.getMessage());
            throw new CommException(ResultCodeEnum.ERROR);
        }
    }

    private static class OkHttpClientHolder {
        private static final OkHttpClient defaultClient;

        private OkHttpClientHolder() {
        }

        static {
            defaultClient = (new okhttp3.OkHttpClient.Builder()).retryOnConnectionFailure(true).connectionPool(new ConnectionPool()).readTimeout(20L, TimeUnit.SECONDS).connectTimeout(20L, TimeUnit.SECONDS).writeTimeout(20L, TimeUnit.SECONDS).build();
        }
    }
}
